package com.papercutting.platform.controller;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.dto.query.CultureQuery;
import com.papercutting.platform.dto.request.CultureRequest;
import com.papercutting.platform.dto.response.CultureResponse;
import com.papercutting.platform.dto.response.PageResult;
import com.papercutting.platform.service.CultureService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 剪纸文化控制器 - 重构为符合三层架构规范
 */
@Slf4j
@RestController
@RequestMapping("/api/culture")
@RequiredArgsConstructor
@Validated
public class CultureController {
    
    private final CultureService cultureService;
    
    /**
     * 获取文化列表
     */
    @GetMapping("/list")
    public Result<PageResult<CultureResponse>> getCultureList(CultureQuery query) {
        log.info("分页查询文化列表: {}", query);
        
        PageResult<CultureResponse> result = cultureService.getCulturePage(query);
        
        return Result.success(result);
    }
    
    /**
     * 获取文化详情
     */
    @GetMapping("/{id}")
    public Result<CultureResponse> getCultureDetail(@PathVariable Long id) {
        log.info("获取文化详情: {}", id);
        
        CultureResponse culture = cultureService.getCultureById(id);
        
        return Result.success(culture);
    }
    
    /**
     * 获取推荐内容
     */
    @GetMapping("/recommend")
    public Result<List<CultureResponse>> getRecommendList(@RequestParam(defaultValue = "5") Integer limit) {
        log.info("获取推荐文化列表: {}", limit);
        
        List<CultureResponse> recommendList = cultureService.getRecommendedCultures(limit);
        
        return Result.success(recommendList);
    }
    
    /**
     * 点赞操作（Toggle模式：点赞/取消点赞）
     */
    @PostMapping("/{id}/like")
    public Result<Map<String, Object>> likeCulture(@PathVariable Long id, 
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        log.info("文化点赞切换操作: id={}", id);
        
        try {
            if (authHeader == null || authHeader.trim().isEmpty()) {
                log.error("Authorization头为空");
                return Result.error("未授权访问");
            }
            
            String token = authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;
            
            Map<String, Object> result = cultureService.likeCulture(token, id);
            log.info("点赞切换操作完成: {}", result);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("点赞操作失败: ", e);
            return Result.error("点赞操作失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消点赞操作（独立接口）
     */
    @DeleteMapping("/{id}/like")
    public Result<Map<String, Object>> unlikeCulture(@PathVariable Long id, 
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        log.info("文化取消点赞操作: id={}", id);
        
        try {
            if (authHeader == null || authHeader.trim().isEmpty()) {
                log.error("Authorization头为空");
                return Result.error("未授权访问");
            }
            
            String token = authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;
            
            Map<String, Object> result = cultureService.unlikeCulture(token, id);
            log.info("取消点赞操作完成: {}", result);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("取消点赞操作失败: ", e);
            return Result.error("取消点赞操作失败: " + e.getMessage());
        }
    }
    
    /**
     * 收藏操作
     */
    @PostMapping("/{id}/favorite")
    public Result<Map<String, Object>> favoriteCulture(@PathVariable Long id,
            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        log.info("文化收藏操作: id={}, authHeader={}", id, authHeader != null ? authHeader.substring(0, Math.min(20, authHeader.length())) + "..." : "null");
        
        try {
            if (authHeader == null || authHeader.trim().isEmpty()) {
                log.error("Authorization头为空");
                return Result.error("未授权访问");
            }
            
            String token = authHeader.startsWith("Bearer ") ? authHeader.substring(7) : authHeader;
            log.info("提取的token: {}...", token.substring(0, Math.min(20, token.length())));
            
            Map<String, Object> result = cultureService.favoriteCulture(token, id);
            log.info("收藏操作成功: {}", result);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("收藏操作失败: ", e);
            return Result.error("收藏操作失败: " + e.getMessage());
        }
    }
    
    /**
     * 搜索文化内容
     */
    @GetMapping("/search")
    public Result<PageResult<CultureResponse>> searchCulture(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        log.info("搜索文化内容: keyword={}, page={}, size={}", keyword, page, size);
        
        CultureQuery query = new CultureQuery();
        query.setKeyword(keyword);
        query.setPage(page);
        query.setSize(size);
        
        PageResult<CultureResponse> result = cultureService.searchCulture(keyword, query);
        
        return Result.success(result);
    }
    
    /**
     * 获取分类统计
     */
    @GetMapping("/category-stats")
    public Result<List<Map<String, Object>>> getCategoryStats() {
        List<Map<String, Object>> stats = cultureService.getCategoryStats();
        return Result.success(stats);
    }
    
    /**
     * 记录浏览
     */
    @PostMapping("/{id}/view")
    public Result<Void> recordView(@PathVariable Long id) {
        log.info("记录浏览: {}", id);
        cultureService.recordView(id);
        return Result.success();
    }
    
    /**
     * 增加分享数
     */
    @PostMapping("/{id}/share")
    public Result<Void> shareContent(@PathVariable Long id) {
        log.info("分享内容: {}", id);
        cultureService.increaseShareCount(id);
        return Result.success();
    }
    
    /**
     * 获取相关文化内容
     */
    @GetMapping("/related")
    public Result<List<CultureResponse>> getRelatedCultures(
            @RequestParam Long id,
            @RequestParam Integer category,
            @RequestParam(defaultValue = "5") Integer limit) {
        log.info("获取相关文化内容: id={}, category={}, limit={}", id, category, limit);
        
        List<CultureResponse> relatedList = cultureService.getRelatedCultures(id, category, limit);
        
        return Result.success(relatedList);
    }
    
    /**
     * 检查用户交互状态
     */
    @GetMapping("/{id}/interaction-status")
    public Result<Map<String, Object>> checkInteractionStatus(@PathVariable Long id,
            @RequestHeader("Authorization") String authHeader) {
        log.info("检查交互状态: id={}", id);
        
        String token = authHeader.replace("Bearer ", "");
        Map<String, Object> status = cultureService.checkUserInteractionStatus(token, id);
        
        return Result.success(status);
    }
}